package fi.iki.juri.units;

import java.util.ArrayList;
import java.util.Collection;


public class Unit {
	private final Collection<Conversion> edges;
	private final String name;
	private Unit baseUnit;
	
	public Unit(final String name) {
		this.name = name;
		this.edges = new ArrayList<Conversion>();
		this.baseUnit = null;
	}

	protected void addEdge(final Conversion converter) {
		edges.add(converter);
	}
	
	protected Iterable<Conversion> getEdges() {
		return edges;
	}

	public String getName() {
		return name;
	}
		
	public void deriveUnit(final Unit baseUnit, final Calculation fromCalc, final Calculation toCalc) {
		if (this.baseUnit != null) {
			throw new RuntimeException(String.format("Unit %s: trying to set baseUnit to %s, but already is %s", 
					this.name, baseUnit.getName(), this.baseUnit.getName()));
		} else if (baseUnit != null) {
			this.baseUnit = baseUnit;
			baseUnit.addEdge(new Conversion(this, fromCalc));
			edges.add(new Conversion(baseUnit, toCalc));
		}		
	}
	
	public String toString() {
		return String.format("<Unit: %s>", name);
	}
}
